﻿using Common;
using Common.Enums;
using Common.Exceptions;
using Common.Utils;
using Library.Entity;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Wallpaper.Data.Context;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Responses.Admin;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class AdminService : IAdminService
    {
        private readonly WallpaperDbContext _dbContext;
        private readonly IJwtService _jwtService; // 添加 JWT 服务依赖
        protected readonly DbSet<Admin> _dbSet;
        readonly IAdminDal _adminDal;

        public AdminService(WallpaperDbContext dbContext, IJwtService jwtService, IAdminDal adminDal) // 注入 IJwtService
        {
            _dbContext = dbContext;
            _jwtService = jwtService;
            _dbSet = dbContext.Set<Admin>();
            _adminDal = adminDal;
        }

        public async Task<string> LoginAsync(string account, string password)
        {
            // 参数验证
            if (string.IsNullOrEmpty(account) || string.IsNullOrEmpty(password))
            {
                throw new BusinessException("账号或密码不能为空", BusinessErrorCode.ACCOUNT_NOT_NULL);
            }

            // 根据账号查询管理员信息
            Admin info = await _dbSet.FirstOrDefaultAsync(a => a.Account == account);

            // 检查账号是否存在
            if (info == null)
            {
                throw new BusinessException("账号或密码错误", BusinessErrorCode.ACCOUNT_ERROR);
            }

            // 检查账号状态是否启用
            if (!info.IsEnabled)
            {
                throw new BusinessException("账户已被禁用", BusinessErrorCode.ACCOUNT_DISABLED_ERROR);
            }

            // 对输入的密码进行MD5加密
            string encryptedPassword = MD5Helper.MD5Encrypt64(password);

            // 验证密码是否正确
            if (info.PasswordHash != encryptedPassword)
            {
                throw new BusinessException("账号或密码错误", BusinessErrorCode.ACCOUNT_ERROR);
            }

            Role role = await _adminDal.GetDbSet<Role>().Where(r => r.Id == info.RoleId).FirstOrDefaultAsync();
            // 使用 IJwtService 生成管理员 Token
            var token = _jwtService.GenerateAdminToken(info, role.RoleCode);
            return token;
        }

        public async Task<AdminResponse> GetInfoAsync(string id)
        {
           Admin admin= await _adminDal.GetByIdAsync(id);
            return new AdminResponse
            {
                Account = admin.Account,
                AvatarUrl = admin.AvatarUrl
            };
        }
    }
}